package setting

import (
	"code.gitea.io/gitea/modules/log"
)

const (
	DEVCONTAINER_AGENT_NAME_K8S    string = "k8s"
	DEVCONTAINER_AGENT_NAME_DOCKER string = "docker"
)

// package 内部私有变量，是一个 Set 结构，标识目前系统所有支持的 DevContainer Agent 类型
var validDevcontainerAgentSet = map[string]struct{}{
	DEVCONTAINER_AGENT_NAME_K8S:    {},
	DEVCONTAINER_AGENT_NAME_DOCKER: {},
}

const (
	CLOUD_PROVIDER_TENCENT = "tencent"
)

// validCloudProviderSet 私有 Set 结构，标识目前系统所有支持的 Cloud Provider 类型
var validCloudProviderSet = map[string]struct{}{
	CLOUD_PROVIDER_TENCENT: {},
}

var Devstar = struct {
	Devcontainer DevcontainerType `ini:"devstar.devcontainer"`
	SSHKeypair   SSHKeyPairType   `ini:"devstar.ssh_key_pair"`
	Cloud        CloudType        `ini:"devstar.cloud"`
}{
	Devcontainer: DevcontainerType{
		Enabled:        false,
		Namespace:      "default",
		TimeoutSeconds: 900, // 最长等待 DevContainer 就绪时间（阻塞式），默认15分钟，可被 app.ini 指定值覆盖

		// 获取 .devcontainer/devcontainer.json 默认分支名称
		DefaultGitBranchName: "main",

		// 若 .devcontainer/devcontainer.json 默认分支未指定 DevContainer Image (`image`)，则使用如下默认值
		// 注： 该镜像必须含有 OpenSSH 服务器程序，否则需要手动制作
		//   手动制作方式参考： https://gitee.com/devstar/devcontainer-tweak
		DefaultDevcontainerImageName: "devstar.cn/public/base-ssh-devcontainer:ubuntu-20.04-20241014",
	},
	SSHKeypair: SSHKeyPairType{
		KeySize: 2048,
	},
	Cloud: CloudType{
		Enabled: false,
	},
}

type DevcontainerType struct {
	Enabled        bool
	Host           string
	Agent          string
	Namespace      string
	TimeoutSeconds int64

	DefaultGitBranchName         string
	DefaultDevcontainerImageName string
	DockerHost                   string
}

type SSHKeyPairType struct {
	KeySize int
}

type CloudType struct {
	Enabled  bool
	Provider string
	Tencent  CloudProviderTencentType `ini:"devstar.cloud.tencent"`
}

type CloudProviderTencentType struct {
	Endpoint         string
	Region           string
	NatGatewayId     string
	PublicIpAddress  string
	PrivateIpAddress string
	IpProtocol       string
	SecretId         string
	SecretKey        string
}

// validateDevstarDevcontainerSettings 检查从 ini 配置文件中读取 DevStar DevContainer 配置信息，若数据无效，则自动禁用 DevContainer
func validateDevstarDevcontainerSettings() {

	// 检查 Host 是否为空，若为空，则自动将 DevContainer 设置为禁用
	if len(Devstar.Devcontainer.Host) == 0 {
		log.Warn("INVALID config 'host' for DevStar DevContainer")
		Devstar.Devcontainer.Enabled = false
	}

	// 检查用户输入的 DevContainer Agent 是否存在支持列表，若不支持，则将 DevContainer 设置为禁用
	if _, exists := validDevcontainerAgentSet[Devstar.Devcontainer.Agent]; !exists {
		log.Warn("INVALID config 'agent' for DevStar DevContainer")
		Devstar.Devcontainer.Enabled = false
	}

	// 检查默认分支名称设置
	if len(Devstar.Devcontainer.DefaultGitBranchName) == 0 {
		log.Warn("INVALID config 'DefaultGitBranchName' for DevStar DevContainer")
		Devstar.Devcontainer.Enabled = false
	}

	// 检查默认 DevContainer Image
	if len(Devstar.Devcontainer.DefaultDevcontainerImageName) == 0 {
		log.Warn("INVALID config 'DefaultGitBranchNameDefaultDevcontainerImageName' for DevStar DevContainer")
		Devstar.Devcontainer.Enabled = false
	}

	if Devstar.Devcontainer.Enabled == false {
		log.Warn("DevStar DevContainer Service Disabled")
	} else {
		log.Info("DevStar DevContainer Service Enabled")
	}
}

// validateDevstarSSHKeyPairSettings 检查从 ini 配置文件中读取 DevStar SSH Key Pair 配置信息
func validateDevstarSSHKeyPairSettings() {
	if Devstar.SSHKeypair.KeySize < 1024 {
		Devstar.SSHKeypair.KeySize = 1024
	}
}

// validateDevstarCloudSettings 检查从 ini 配置文件中读取 DevStar Cloud 配置信息
func validateDevstarCloudSettings() {
	switch Devstar.Cloud.Provider {
	case CLOUD_PROVIDER_TENCENT:
		// 腾讯云配置检查

		if len(Devstar.Cloud.Tencent.NatGatewayId) < 4 {
			log.Warn("INVALID NAT Gateway ID '%v' for DevStar Cloud Provider Tencent", Devstar.Cloud.Tencent.NatGatewayId)
			Devstar.Cloud.Enabled = false
		}

		if Devstar.Cloud.Tencent.IpProtocol != "TCP" && Devstar.Cloud.Tencent.IpProtocol != "UDP" {
			log.Warn("INVALID IP Protocol '%v' for DevStar Cloud Provider Tencent", Devstar.Cloud.Tencent.IpProtocol)
			Devstar.Cloud.Enabled = false
		}

		if len(Devstar.Cloud.Tencent.Region) < 3 || len(Devstar.Cloud.Tencent.Endpoint) == 0 {
			log.Warn("INVALID (Region, Endpoint) pair ('%v', '%v') for DevStar Cloud Provider Tencent",
				Devstar.Cloud.Tencent.Region, Devstar.Cloud.Tencent.Endpoint)
			Devstar.Cloud.Enabled = false
		}

		if len(Devstar.Cloud.Tencent.PrivateIpAddress) == 0 || len(Devstar.Cloud.Tencent.PublicIpAddress) == 0 {
			log.Warn("INVALID (PublicIpAddress, PrivateIpAddress) pair ('%v', '%v') for DevStar Cloud Provider Tencent",
				Devstar.Cloud.Tencent.PublicIpAddress, Devstar.Cloud.Tencent.PrivateIpAddress)
			Devstar.Cloud.Enabled = false
		}

		if len(Devstar.Cloud.Tencent.SecretId) == 0 || len(Devstar.Cloud.Tencent.SecretKey) == 0 {
			log.Warn("INVALID (SecretId, SecretKey) pair for DevStar Cloud Provider Tencent")
			Devstar.Cloud.Enabled = false
		}

	default:
		// 无效 Cloud Provider 名称
		log.Warn("INVALID config '%v' for DevStar Cloud", Devstar.Cloud.Provider)
		Devstar.Cloud.Enabled = false
	}

	if Devstar.Cloud.Enabled == false {
		log.Warn("DevStar Cloud Provider Service Disabled")
	} else {
		log.Info("DevStar Cloud Provider '%v' Enabled", Devstar.Cloud.Provider)
	}

}

func loadDevstarFrom(rootCfg ConfigProvider) {
	mustMapSetting(rootCfg, "devstar", &Devstar)

	validateDevstarDevcontainerSettings()
	validateDevstarSSHKeyPairSettings()
	validateDevstarCloudSettings()
}
